//
//  CorgiTabBar.swift
//  weibo
//
//  Created by Corgi on 17/3/19.
//  Copyright © 2017年 cocoaHangTou. All rights reserved.
//

import UIKit

class CorgiTabBar: UITabBar {

    //准备闭包
    var clickClosure: ((CorgiTabBar) -> ())?
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        addSubview(midBtn)
        
        midBtn.addTarget(self, action: #selector(midBtnClick), for: .touchUpInside)
    }
    
    @objc private func midBtnClick() {
        
        clickClosure?(self)
        
    }
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //重新布局tabBarButton
        let itemWidth = bounds.width * 0.2
        
        let itemHeight = bounds.height
        
        var index = 0
        
        for subview in subviews {
        
            if subview.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                subview.frame = CGRect(x: CGFloat(index) * itemWidth, y: 0, width: itemWidth, height: itemHeight)
                
                index += (index == 1 ? 2 : 1)
            }
        
        }
        
        midBtn.center = CGPoint(x: center.x, y: bounds.height * 0.5)
        
        midBtn.bounds.size = CGSize(width: itemWidth, height: itemHeight)
    
    }
    
    lazy var midBtn: UIButton = {
    
        //添加button
        var btn = UIButton()
        
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .selected)
        
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .selected)
       
        return btn
    }()
    

}
